<template>
    <view class="container">
        <!-- 自定义导航栏 -->
        <custom-navbar title="消息"></custom-navbar>
        
        <!-- 主内容区域 -->
        <scroll-view 
            class="main-content" 
            :style="{paddingTop: navbarTotalHeight + 'px'}"
            scroll-y="true"
            refresher-enabled="true"
            :refresher-triggered="refreshing"
            @refresherrefresh="onPullDownRefresh"
        >
            <!-- 搜索框 -->
            <view class="search-container">
                <view class="search-box">
                    <image class="search-icon" src="https://img.icons8.com/ios/50/search--v1.png" mode="aspectFit"></image>
                    <input 
                        class="search-input" 
                        placeholder="搜索消息..." 
                        placeholder-style="color: #999;"
                        v-model="searchKeyword"
                        @input="onSearchInput"
                    />
                    <view class="search-clear" v-if="searchKeyword" @tap="clearSearch">
                        <image class="clear-icon" src="https://img.icons8.com/ios/50/delete-sign.png" mode="aspectFit"></image>
                    </view>
                </view>
            </view>

            <!-- 消息分类标签 -->
            <view class="message-tabs">
                <view 
                    class="tab-item" 
                    :class="{active: activeTab === index}" 
                    v-for="(tab, index) in messageTabs" 
                    :key="index"
                    @tap="switchTab(index)"
                >
                    <text class="tab-text">{{tab.name}}</text>
                    <view class="tab-badge" v-if="tab.unreadCount > 0">
                        <text class="badge-text">{{tab.unreadCount > 99 ? '99+' : tab.unreadCount}}</text>
                    </view>
                </view>
            </view>

            <!-- 消息列表 -->
            <view class="messages-list">
                <view 
                    class="message-item" 
                    v-for="(message, index) in filteredMessages" 
                    :key="index"
                    @tap="openMessage(message)"
                    @longpress="showMessageMenu(message, index)"
                >
                    <!-- 消息头像 -->
                    <view class="message-avatar">
                        <image class="avatar-img" :src="message.avatar" mode="aspectFit"></image>
                        <view class="online-status" v-if="message.isOnline"></view>
                        <view class="unread-dot" v-if="!message.isRead"></view>
                    </view>
                    
                    <!-- 消息内容 -->
                    <view class="message-content">
                        <view class="message-header">
                            <text class="sender-name">{{message.senderName}}</text>
                            <text class="message-time">{{formatTime(message.time)}}</text>
                        </view>
                        <view class="message-preview">
                            <text class="preview-text" :class="{unread: !message.isRead}">{{getMessagePreview(message)}}</text>
                        </view>
                        <view class="message-meta" v-if="message.type !== 'text'">
                            <image class="meta-icon" :src="getMessageTypeIcon(message.type)" mode="aspectFit"></image>
                            <text class="meta-text">{{getMessageTypeText(message.type)}}</text>
                        </view>
                    </view>
                    
                    <!-- 消息状态 -->
                    <view class="message-status">
                        <view class="unread-count" v-if="message.unreadCount > 0">
                            <text class="count-text">{{message.unreadCount > 99 ? '99+' : message.unreadCount}}</text>
                        </view>
                        <image 
                            class="message-type-icon" 
                            v-if="message.isPinned"
                            src="https://img.icons8.com/ios/50/pin.png" 
                            mode="aspectFit"
                        ></image>
                    </view>
                </view>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-if="filteredMessages.length === 0 && !isLoading">
                <image class="empty-icon" src="https://img.icons8.com/fluency/96/no-messages.png" mode="aspectFit"></image>
                <text class="empty-text">{{searchKeyword ? '没有找到相关消息' : '暂无消息'}}</text>
                <text class="empty-desc">{{searchKeyword ? '尝试搜索其他关键词' : '开始与朋友聊天吧！'}}</text>
            </view>

            <!-- 加载更多 -->
            <view class="load-more" v-if="hasMore && filteredMessages.length > 0">
                <text class="load-text">{{loadingText}}</text>
            </view>
        </scroll-view>

        <!-- 消息操作菜单 -->
        <view class="message-menu-mask" v-if="showMenu" @tap="hideMessageMenu"></view>
        <view class="message-menu" v-if="showMenu" :style="{bottom: menuBottom + 'px'}">
            <view class="menu-item" @tap="markAsRead">
                <image class="menu-icon" src="https://img.icons8.com/ios/50/checkmark.png" mode="aspectFit"></image>
                <text class="menu-text">标记为已读</text>
            </view>
            <view class="menu-item" @tap="pinMessage">
                <image class="menu-icon" src="https://img.icons8.com/ios/50/pin.png" mode="aspectFit"></image>
                <text class="menu-text">{{selectedMessage?.isPinned ? '取消置顶' : '置顶'}}</text>
            </view>
            <view class="menu-item danger" @tap="deleteMessage">
                <image class="menu-icon" src="https://img.icons8.com/ios/50/trash.png" mode="aspectFit"></image>
                <text class="menu-text">删除</text>
            </view>
        </view>

        <!-- 自定义底部导航栏 -->
        <custom-tabbar :current="3" @switch="onTabSwitch"></custom-tabbar>
    </view>
</template>

<script>
import CustomNavbar from '@/components/custom-navbar/custom-navbar.vue';
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue';

export default {
    components: {
        CustomNavbar,
        CustomTabbar
    },
    data() {
        return {
            navbarTotalHeight: 132,
            statusBarHeight: 44,
            refreshing: false,
            isLoading: false,
            hasMore: true,
            loadingText: '上拉加载更多',
            searchKeyword: '',
            activeTab: 0,
            showMenu: false,
            selectedMessage: null,
            selectedIndex: -1,
            menuBottom: 140,
            
            // 消息分类
            messageTabs: [
                { name: '全部', unreadCount: 5 },
                { name: '系统', unreadCount: 2 },
                { name: '好友', unreadCount: 3 },
                { name: '群聊', unreadCount: 0 }
            ],
            
            // 消息列表
            messagesList: [
                {
                    id: 1,
                    senderName: '系统通知',
                    avatar: 'https://img.icons8.com/fluency/48/bell.png',
                    type: 'system',
                    category: 'system',
                    content: '您的帖子《最近看了一部超好看的电影！》获得了10个赞',
                    time: new Date().getTime() - 1000 * 60 * 30, // 30分钟前
                    isRead: false,
                    isOnline: false,
                    unreadCount: 1,
                    isPinned: true
                },
                {
                    id: 2,
                    senderName: '影视迷',
                    avatar: 'https://img.icons8.com/fluency/48/user.png',
                    type: 'text',
                    category: 'friend',
                    content: '那部电影真的很不错，感谢推荐！',
                    time: new Date().getTime() - 1000 * 60 * 60 * 2, // 2小时前
                    isRead: false,
                    isOnline: true,
                    unreadCount: 2,
                    isPinned: false
                },
                {
                    id: 3,
                    senderName: '懒人交流群',
                    avatar: 'https://img.icons8.com/fluency/48/conference-call.png',
                    type: 'text',
                    category: 'group',
                    content: '小白: 大家好，新人报到！',
                    time: new Date().getTime() - 1000 * 60 * 60 * 5, // 5小时前
                    isRead: true,
                    isOnline: false,
                    unreadCount: 0,
                    isPinned: false
                },
                {
                    id: 4,
                    senderName: '电影发烧友',
                    avatar: 'https://img.icons8.com/fluency/48/user-male.png',
                    type: 'image',
                    category: 'friend',
                    content: '发送了一张图片',
                    time: new Date().getTime() - 1000 * 60 * 60 * 24, // 1天前
                    isRead: true,
                    isOnline: false,
                    unreadCount: 0,
                    isPinned: false
                },
                {
                    id: 5,
                    senderName: '系统消息',
                    avatar: 'https://img.icons8.com/fluency/48/info.png',
                    type: 'system',
                    category: 'system',
                    content: '您的账户安全等级已提升',
                    time: new Date().getTime() - 1000 * 60 * 60 * 24 * 2, // 2天前
                    isRead: false,
                    isOnline: false,
                    unreadCount: 1,
                    isPinned: false
                }
            ]
        }
    },
    computed: {
        // 过滤后的消息列表
        filteredMessages() {
            let messages = this.messagesList;
            
            // 按分类过滤
            if (this.activeTab > 0) {
                const category = ['all', 'system', 'friend', 'group'][this.activeTab];
                messages = messages.filter(msg => msg.category === category);
            }
            
            // 按搜索关键词过滤
            if (this.searchKeyword.trim()) {
                const keyword = this.searchKeyword.toLowerCase();
                messages = messages.filter(msg => 
                    msg.senderName.toLowerCase().includes(keyword) ||
                    msg.content.toLowerCase().includes(keyword)
                );
            }
            
            // 置顶消息排在前面，然后按时间排序
            return messages.sort((a, b) => {
                if (a.isPinned && !b.isPinned) return -1;
                if (!a.isPinned && b.isPinned) return 1;
                return b.time - a.time;
            });
        }
    },
    mounted() {
        const systemInfo = uni.getSystemInfoSync();
        this.statusBarHeight = systemInfo.statusBarHeight || 44;
        this.navbarTotalHeight = this.statusBarHeight + 44;
    },
    methods: {
        // 下拉刷新
        onPullDownRefresh() {
            this.refreshing = true;
            setTimeout(() => {
                this.loadMessagesData();
                this.refreshing = false;
                uni.showToast({
                    title: '刷新成功',
                    icon: 'success',
                    duration: 1000
                });
            }, 1500);
        },
        
        // 加载消息数据
        loadMessagesData() {
            // 模拟新增消息
            const newMessage = {
                id: this.messagesList.length + 1,
                senderName: '新用户',
                avatar: 'https://img.icons8.com/fluency/48/person.png',
                type: 'text',
                category: 'friend',
                content: '刚刚',
                time: new Date().getTime(),
                isRead: false,
                isOnline: true,
                unreadCount: 1,
                isPinned: false
            };
            this.messagesList.unshift(newMessage);
            
            // 更新未读数量
            this.messageTabs[0].unreadCount++;
            this.messageTabs[2].unreadCount++;
        },
        
        // 搜索输入
        onSearchInput() {
            // 实时搜索逻辑
        },
        
        // 清空搜索
        clearSearch() {
            this.searchKeyword = '';
        },
        
        // 切换标签
        switchTab(index) {
            this.activeTab = index;
        },
        
        // 打开消息
        openMessage(message) {
            // 标记为已读
            if (!message.isRead) {
                message.isRead = true;
                message.unreadCount = 0;
                this.updateUnreadCount();
            }
            
            // 跳转到聊天页面
            uni.navigateTo({
                url: `/pages/chat/chat?messageId=${message.id}`
            });
        },
        
        // 显示消息菜单
        showMessageMenu(message, index) {
            this.selectedMessage = message;
            this.selectedIndex = index;
            this.showMenu = true;
            
            uni.vibrateShort(); // 震动反馈
        },
        
        // 隐藏消息菜单
        hideMessageMenu() {
            this.showMenu = false;
            this.selectedMessage = null;
            this.selectedIndex = -1;
        },
        
        // 标记为已读
        markAsRead() {
            if (this.selectedMessage) {
                this.selectedMessage.isRead = true;
                this.selectedMessage.unreadCount = 0;
                this.updateUnreadCount();
            }
            this.hideMessageMenu();
        },
        
        // 置顶/取消置顶
        pinMessage() {
            if (this.selectedMessage) {
                this.selectedMessage.isPinned = !this.selectedMessage.isPinned;
                uni.showToast({
                    title: this.selectedMessage.isPinned ? '已置顶' : '已取消置顶',
                    icon: 'success'
                });
            }
            this.hideMessageMenu();
        },
        
        // 删除消息
        deleteMessage() {
            if (this.selectedIndex >= 0) {
                uni.showModal({
                    title: '确认删除',
                    content: '删除后无法恢复，确定要删除这条消息吗？',
                    success: (res) => {
                        if (res.confirm) {
                            this.messagesList.splice(this.selectedIndex, 1);
                            this.updateUnreadCount();
                            uni.showToast({
                                title: '删除成功',
                                icon: 'success'
                            });
                        }
                    }
                });
            }
            this.hideMessageMenu();
        },
        
        // 更新未读数量
        updateUnreadCount() {
            this.messageTabs.forEach((tab, index) => {
                if (index === 0) {
                    // 全部
                    tab.unreadCount = this.messagesList.filter(msg => !msg.isRead).length;
                } else {
                    const category = ['all', 'system', 'friend', 'group'][index];
                    tab.unreadCount = this.messagesList.filter(msg => 
                        msg.category === category && !msg.isRead
                    ).length;
                }
            });
        },
        
        // 格式化时间
        formatTime(timestamp) {
            const now = new Date().getTime();
            const diff = now - timestamp;
            const minute = 1000 * 60;
            const hour = minute * 60;
            const day = hour * 24;
            
            if (diff < minute) {
                return '刚刚';
            } else if (diff < hour) {
                return Math.floor(diff / minute) + '分钟前';
            } else if (diff < day) {
                return Math.floor(diff / hour) + '小时前';
            } else if (diff < day * 7) {
                return Math.floor(diff / day) + '天前';
            } else {
                const date = new Date(timestamp);
                return `${date.getMonth() + 1}/${date.getDate()}`;
            }
        },
        
        // 获取消息预览
        getMessagePreview(message) {
            if (message.type === 'text') {
                return message.content;
            } else if (message.type === 'image') {
                return '[图片]';
            } else if (message.type === 'system') {
                return message.content;
            }
            return message.content;
        },
        
        // 获取消息类型图标
        getMessageTypeIcon(type) {
            const icons = {
                'image': 'https://img.icons8.com/ios/50/image.png',
                'video': 'https://img.icons8.com/ios/50/video.png',
                'audio': 'https://img.icons8.com/ios/50/microphone.png',
                'file': 'https://img.icons8.com/ios/50/document.png'
            };
            return icons[type] || 'https://img.icons8.com/ios/50/message.png';
        },
        
        // 获取消息类型文本
        getMessageTypeText(type) {
            const texts = {
                'image': '[图片]',
                'video': '[视频]',
                'audio': '[语音]',
                'file': '[文件]'
            };
            return texts[type] || '';
        },
        
        // Tab切换事件
        onTabSwitch(event) {
            console.log('Tab切换:', event);
        }
    }
}
</script>

<style scoped>
.container {
    background-color: #f5f5f5;
    min-height: 100vh;
}

.main-content {
    height: calc(100vh - 132rpx - 120rpx);
    padding-bottom: 140rpx;
}

/* 搜索框 */
.search-container {
    background: #ffffff;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.search-box {
    display: flex;
    align-items: center;
    background: #f8f9fa;
    border-radius: 25rpx;
    padding: 0 30rpx;
    height: 70rpx;
}

.search-icon {
    width: 28rpx;
    height: 28rpx;
    margin-right: 15rpx;
    opacity: 0.6;
}

.search-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
}

.search-clear {
    padding: 10rpx;
}

.clear-icon {
    width: 24rpx;
    height: 24rpx;
    opacity: 0.4;
}

/* 消息分类标签 */
.message-tabs {
    display: flex;
    background: #ffffff;
    padding: 20rpx 30rpx 10rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.tab-item {
    position: relative;
    margin-right: 40rpx;
    padding: 15rpx 20rpx;
    border-radius: 20rpx;
    transition: all 0.3s ease;
}

.tab-item.active {
    background: #667eea;
}

.tab-text {
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s ease;
}

.tab-item.active .tab-text {
    color: #ffffff;
    font-weight: bold;
}

.tab-badge {
    position: absolute;
    top: 5rpx;
    right: 5rpx;
    background: #ff4757;
    border-radius: 15rpx;
    min-width: 30rpx;
    height: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8rpx;
}

.badge-text {
    color: #ffffff;
    font-size: 20rpx;
    font-weight: bold;
}

/* 消息列表 */
.messages-list {
    background: #ffffff;
}

.message-item {
    display: flex;
    align-items: center;
    padding: 25rpx 30rpx;
    border-bottom: 1rpx solid #f8f9fa;
    transition: all 0.3s ease;
    position: relative;
}

.message-item:active {
    background: #f8f9fa;
}

.message-item:last-child {
    border-bottom: none;
}

/* 消息头像 */
.message-avatar {
    position: relative;
    margin-right: 25rpx;
}

.avatar-img {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background: #f0f0f0;
}

.online-status {
    position: absolute;
    bottom: 5rpx;
    right: 5rpx;
    width: 20rpx;
    height: 20rpx;
    background: #2ed573;
    border-radius: 50%;
    border: 3rpx solid #ffffff;
}

.unread-dot {
    position: absolute;
    top: 5rpx;
    right: 5rpx;
    width: 16rpx;
    height: 16rpx;
    background: #ff4757;
    border-radius: 50%;
}

/* 消息内容 */
.message-content {
    flex: 1;
    min-width: 0;
}

.message-header {
    display: flex;
    align-items: center;
    margin-bottom: 8rpx;
}

.sender-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-right: 20rpx;
}

.message-time {
    font-size: 22rpx;
    color: #999;
    margin-left: auto;
}

.message-preview {
    margin-bottom: 5rpx;
}

.preview-text {
    font-size: 28rpx;
    color: #666;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.preview-text.unread {
    color: #333;
    font-weight: 500;
}

.message-meta {
    display: flex;
    align-items: center;
}

.meta-icon {
    width: 24rpx;
    height: 24rpx;
    margin-right: 8rpx;
    opacity: 0.6;
}

.meta-text {
    font-size: 24rpx;
    color: #999;
}

/* 消息状态 */
.message-status {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10rpx;
}

.unread-count {
    background: #ff4757;
    border-radius: 15rpx;
    min-width: 30rpx;
    height: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8rpx;
}

.count-text {
    color: #ffffff;
    font-size: 20rpx;
    font-weight: bold;
}

.message-type-icon {
    width: 24rpx;
    height: 24rpx;
    opacity: 0.6;
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 100rpx 40rpx;
}

.empty-icon {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 30rpx;
    opacity: 0.6;
}

.empty-text {
    display: block;
    font-size: 32rpx;
    color: #666;
    margin-bottom: 15rpx;
}

.empty-desc {
    display: block;
    font-size: 28rpx;
    color: #999;
}

/* 加载更多 */
.load-more {
    text-align: center;
    padding: 40rpx;
}

.load-text {
    color: #999;
    font-size: 28rpx;
}

/* 消息操作菜单 */
.message-menu-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    z-index: 9998;
}

.message-menu {
    position: fixed;
    left: 30rpx;
    right: 30rpx;
    background: #ffffff;
    border-radius: 20rpx;
    z-index: 9999;
    animation: slideUp 0.3s ease;
    box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
}

.menu-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    transition: all 0.3s ease;
}

.menu-item:last-child {
    border-bottom: none;
}

.menu-item:active {
    background: #f8f9fa;
}

.menu-item.danger .menu-text {
    color: #ff4757;
}

.menu-icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 20rpx;
    opacity: 0.7;
}

.menu-text {
    font-size: 32rpx;
    color: #333;
}

/* 动画效果 */
@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(100rpx);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>